package com.ml.shs.controller;

import com.ml.shs.annotation.LoginAnnotation;
import com.ml.shs.entity.User;
import com.ml.shs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/shs/user")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/login")
    public Map<String, Object> login(@RequestBody User user, HttpSession session) throws Exception{
        User currentUser = userService.login(user);
        session.setAttribute("userId", currentUser.getId());
        session.setAttribute("account", currentUser.getAccount());

        String userName = currentUser.getAccount();
        if(currentUser.getNickName() !=  null){
            userName = currentUser.getNickName();
        }
        session.setAttribute("userName",userName);
        Map<String, Object> response = new HashMap();
        response.put("status", "success");
        response.put("data", currentUser);
        return response;
    }

    @GetMapping("/getInfo")
    @LoginAnnotation(name="没有登陆")
    public Optional<User> getInfo(HttpSession session){
        String userId = (String)session.getAttribute("userId");
        return userService.getInfo(userId);
    }

    @RequestMapping("/update")
    public void  update(@RequestBody User user, HttpSession session) throws Exception{
        String userId = (String)session.getAttribute("userId");
        userService.update(user, userId);
    }

}
